package edu.dayu.controller;

import edu.dayu.pojo.User;
import edu.dayu.service.UserService;
import edu.dayu.util.ClubException;
import edu.dayu.util.Result;
import edu.dayu.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(User user){
        User login = userService.login(user);
        if (login!=null) {
            String refreshToken = UUID.randomUUID() + "";
            String token = UUID.randomUUID() + "";
            redisTemplate.opsForValue().set("refreshToken", refreshToken, 7L, TimeUnit.DAYS);
            redisTemplate.opsForValue().set("token", token, 1L, TimeUnit.DAYS);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("refreshToken", refreshToken);
            login.setPwd(null);
            map.put("user", login);
            return Result.build(map, ResultCodeEnum.SUCCESS);
        }else {
            throw new ClubException(ResultCodeEnum.PARAM_ERROR);
        }
    }


    /**
     * 登出，清除token,只需要前端把 jwt 清除就行了。
     */
    @PostMapping("/logout")
    public void logout(){
        redisTemplate.delete("token");
        redisTemplate.delete("refreshToken");
    }

    /**
     * 符合要求就刷新 token
     * @return
     */
    @PostMapping("/refresh")
    public Result refresh(String refreshToken){
        if (StringUtils.isEmpty(refreshToken))
            throw new ClubException(ResultCodeEnum.FAIL);
        String refreshToken1 = (String)redisTemplate.opsForValue().get("refreshToken");
        if (refreshToken.equals(refreshToken1)){
            String token = UUID.randomUUID() + "";
            redisTemplate.opsForValue().set("token", token, 1L, TimeUnit.DAYS);
            return Result.ok(token);
        }
        return Result.fail();
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String pwd = map.get("pwd");
        boolean res = userService.register(username,pwd);
        if(res){
            return Result.ok();
        }
        return Result.fail();
    }

}
